package com.thread.deadLock;

/**
 * DeadLockRisk--bdqnPractice
 *
 * @author: Jovi
 * @createTime: 2017-08-22 11:28
 **/
public class DeadLockRisk {

    private static class Resource {

        public int value;
    }

    private Resource resourceA = new Resource();

    private Resource resourceB = new Resource();

    public int read() {
        synchronized (resourceA) {
            try {
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getName()+"线程【读】操作获得的resourceA锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (resourceB) {
                System.out.println(Thread.currentThread().getName()+"线程【读】操作获得的resourceB锁");
                return resourceB.value + resourceA.value;
            }
        }
    }

    public void write(int a, int b) {
        synchronized (resourceB) {
            try {
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getName()+"线程【写】操作获得的resourceB锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (resourceA) {
                resourceA.value = a;
                resourceB.value = b;
                System.out.println(Thread.currentThread().getName()+"线程【写】操作获得的resourceA锁");
            }
        }
    }
}
